<?php

namespace app\modules\admin\controllers;

use Yii;
use app\modules\admin\components\ArrayHelper;
use app\modules\admin\models\SysMenuCate;
use app\modules\admin\models\SysMenu;
use yii\web\NotFoundHttpException;
/**
 * Default controller for the `admin` module
 */
class DefaultController extends Controller
{
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['access']['only'] = ['index', 'test', 'main', 'ajax-edit'];
        $behaviors['access']['rules'] = [
            [
                'actions' => ['index', 'test', 'main', 'ajax-edit'],
                'allow' => true,
                'roles' => ['@'],
            ]
        ];
        return $behaviors;
    }
    /**
     * Renders the index view for the module
     * @return string
     */
    public function actionIndex()
    {
    	$this->layout = false;
        return $this->render('index', [
            'model' => SysMenuCate::getList(),
        ]);
    }

    public function actionTest()
    {
        $cate_id = Yii::$app->request->get('cate_id', 1);
        $models = SysMenu::find()->filterWhere(['cate_id' => $cate_id])
                ->orderBy('sort asc, created_at asc')
                ->asArray()
                ->all();
//        var_dump(ArrayHelper::itemsMerge($models));exit;
        return $this->render('test', [
    	    'models' => ArrayHelper::itemsMerge($models),
            'cate_id' => $cate_id,
            'cates' => SysMenuCate::getList(),
        ]);
    }

    public function actionHello()
    {
        return json_encode(SysMenuCate::getList());
    }

    public function actionMain()
    {
        return $this->render('main');
    }

    public function actionAjaxEdit()
    {
//        echo Yii::$app->request->get('cate_id');exit;
        $id = Yii::$app->request->get('id');

        $model = $this->findModel($id);

        $model->level = Yii::$app->request->get('level', null) ?? $model->level; // 级别
        $model->pid = Yii::$app->request->get('pid', null) ?? $model->pid; // 父id
        $model->cate_id = Yii::$app->request->get('cate_id', 0) ?? $model->cate_id; // 分类id
        $model->params = unserialize($model->params);

        if ($model->load(Yii::$app->request->post())) {
            if (Yii::$app->request->isAjax) {
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                return \yii\widgets\ActiveForm::validate($model);
            }
            $model->params = serialize($model->params);
//            $model->params = serialize(Yii::$app->request->post('params'));
            return $model->save() 
            ? $this->redirect(['test', 'cate_id' => $model->cate_id])
            : $this->message($this->analyErr($model->getFirstErrors()), $this->redirect(['test', 'cate_id' => $model->cate_id]), 'error');
        }
        return $this->renderAjax('_form', [
            'model' => $model,
            'parent_title' => Yii::$app->request->get('parent_title', '无'),
        ]);
    }

    public function actionDelete($id)
    {
        $cate_id = Yii::$app->request->get('cate_id');
        if (SysMenu::findOne($id)->delete()) {
            Yii::$app->session->setFlash('success', '删除成功');
            return true;
        } else {
            Yii::$app->getSession()->setFlash('error', '删除失败');
            return false;
        }
    }

    protected function findModel($id)
    {
        $model = SysMenu::findOne($id);
        if (empty($id) || empty($model)) {
            $model = new SysMenu();
            return $model->loadDefaultValues();
        }
        return $model;
//        if ( !empty($id) || ($model = SysMenu::findOne($id)) !== null) {
//            return $model;
//        }

//        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
